package com.yesun.task.pipeline.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置，支持mysql和clickhouse
 */
@Slf4j
@Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class DataSourceConfig {

    @Primary
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql-db")
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }

    @Bean(name = "clickhouseDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.clickhouse-db")
    public DataSource read0DataSource() {
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }

    //以前没有设置bean，导致失败，这个bean必须设置，否则ioc容器中无效
    @Bean
    public DataSource dynamicDataSourceRoute(@Qualifier("mysqlDataSource") DataSource mysqlDataSource,
                                             @Qualifier("clickhouseDataSource") DataSource clickhouseDataSource) {
        Map<Object,Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DBTypeEnum.MYSQL.toString(), mysqlDataSource);//这里还是硬编码了
        targetDataSources.put(DBTypeEnum.CLICKHOUSE.toString(), clickhouseDataSource);
        DynamicDataSourceRoute dynamicDataSourceRoute = new DynamicDataSourceRoute();
        dynamicDataSourceRoute.setDefaultTargetDataSource(mysqlDataSource); //default
        dynamicDataSourceRoute.setTargetDataSources(targetDataSources);
        return dynamicDataSourceRoute;
    }

}
